<?php

namespace app\modules\admin\common;

use app\common\components\BaseWebController;
use app\common\service\UrlService;
use app\models\User;
use app\common\service\applog\ApplogService;

/**
 *
 */
class BaseController extends BaseWebController
{
    public $current_user = null;
    protected $auth_cookie_name = "baoli_user";
    protected $salt = "dm3HsNYz3Uy46Rjg";
    protected $page_size = 6;
    //public $enableCsrfValidation = false;


    public $allowAllAction = [
        'admin/user/login',
        'admin/user/logout'
    ];

    /**
     * @param $id
     * @param $module
     * @param array $config
     */
    public function __construct($id, $module, $config = [])
    {
        parent::__construct($id, $module, $config = []);
        $this->layout = "main";
    }

    //登陆统一验证

    /**
     * @param \yii\base\Action $view
     * @return bool
     */
    public function beforeAction($view)
    {

        if (in_array($this->action->uniqueId, $this->allowAllAction)) {
            return true;
        }

        //验证是否登陆
        $is_login = $this->checkLoginState();

        if (!$is_login) {
            if (\yii::$app->request->isAjax) {
                $this->renderJson([], "请登录", 302);
            } else {
                $this->redirect(UrlService::buildIndexUrl("/"));
            }
            return false;
        }
        return true;
    }

    public function checkLoginState()
    {
        $auth_cookie = $this->getCookie("baoli_user");

        if (!$auth_cookie) {
            return false;
        }

        list($auth_token, $uid) = explode("#", $auth_cookie);
        if (!$auth_token || !$uid) {
            return false;
        }

        if (!preg_match("/^\d+$/", $uid)) {
            return false;
        }

        $user_info = User::find()->where(["uid" => $uid])->one();
        if (!$user_info) {
            return false;
        }

        if ($auth_token != $this->geneAuthToken($user_info)) {
            return false;
        }

        $this->current_user = $user_info;

        ApplogService::addAppLog($this->current_user['uid']);

        return true;

    }

    public function setLoginStatus($user_info)
    {
        $auth_token = $this->geneAuthToken($user_info);
        $this->setCookie($this->auth_cookie_name, $auth_token . "#" . $user_info['uid']);
    }

    protected function removeAuthToken()
    {
        $this->removeCookie($this->auth_cookie_name);
    }

    public function geneAuthToken($user_info)
    {
        return md5($this->salt . "-{$user_info['login_name']}-{$user_info['login_pwd']}-{$user_info['login_salt']}");
    }

    public function getUid()
    {
        return $this->current_user ? $this->current_user['uid'] : 0;
    }
}
